Ext.namespace("Dudley");
Ext.namespace("Dudley.lims");

Dudley.lims.YPGStrain = function() {
    var myYPGData = [];
    var ypgForm = {};
    var ypgPanel = {};
    var ypgHash = null;
    var ypgCount = null;
    var ypgMaxNum = null;
    var ypgStore = null;
    var ypgLoaded = false;
    var searchParam = 'YPG';
    var searchOption = 'ypgFields';
    var pagingBar = null;
    var spotlightMenu = sptlght.utils.SpotlightUtils.getSpotlightMenu("ypgspotlightmenuid");

    function initYPGStore(failedCb, callback) {
        loadYPGSearchResult(0, null, callback);
    }

    function loadYPGSearchResult(index, searchResultJSON, callback) {
   		ypgStore = loadSolrSearchResult("YPG", getYPGPagingColumns(), ypgSolrTranslator, index, searchResultJSON);
		ypgStore.load({params:{start:0, limit:10}}, callback());
        }

    function goSearch(index, ypgSearchInput, ypgSearchOption) {
        if (ypgSearchInput == '') {
        	ypgSearchInput = 'YPG';
        }
        //ypgSearchInput = checkWildcard(ypgSearchInput);
        var searchWin = getSearchLoadingWindow("yprogeny-");        
        var searchUrl = getSolrSearchUrl(getLuceneTerm("ypgFields", ypgSearchInput), 5000, ypgFields);
        searchWin.on("show", function () {
            var sb = Ext.getCmp("yprogeny-search-statusbar");
            sb.showBusy();
        });
        searchWin.show();
        Ext.Ajax.request({
            url: searchUrl,
            method: "GET",
            success: function(response) {
                var searchResultObj = Ext.util.JSON.decode(response.responseText);
                myYPGData = [];
                loadYPGSearchResult(index, searchResultObj.response, function() {
                    Ext.getDom("sample-search-result-list").innerHTML = "";
                    Ext.getDom("yo-form").innerHTML = "";
                    searchWin.close();
                    renderYPGSearchResult();
                });
            },
            failure: function() {
                eventManager.fireStatusMessageEvent({ text: "Search Results failed for url:" + searchUrl, level: "error" });
            }
        });
    }

    function loadYPGPanel() {
    	var ypgSearchForm = getSearchForm("ypgSearchButtonId", "ypgSearchInputId", null);
        Ext.getCmp("ypgSearchButtonId").addListener("click", function(){
			goSearch(0, Ext.getCmp("ypgSearchInputId").getValue(), "ypgFields");		
	   });		
        var tbarButtons = [
            {
                id: 'showYPGSearchResultsId',
                name: 'showYPGSearchResults',
                disabled: true,
                text: '<--Search Results',
                icon: "images/back-green.png",
                cls:'x-btn-text-icon',
                listeners: {click:
                        function() {
                            Ext.getDom("yo-form").innerHTML = "";
                            renderYPGSearchResult();
                        }
                }
            },
            {
                id: 'createNewYPGId',
                name: 'createNewYPG',
                text: 'Create YPG',
                disabled: true,
                icon: "images/add-green.png",
                cls:'x-btn-text-icon',
                listeners: {click:
                        function() {
                            Dudley.lims.YPGStrain.loadNewYPG();
                        }
                }
            },
            {
                id: 'imageYPGId',
                name: 'imageYPG',
                text: 'View Image',
                icon: "images/smart.png",
                cls:'x-btn-text-icon',
                listeners: {click:
                        function() {
                            Dudley.lims.YPGStrain.viewImages();
                        }
                }
            }
        ];
        ypgPanel = new Ext.Panel({
            id: "ypgPanelId",
            autoHeight: true,
            border: true,
            renderTo: "yad-panel",
            title: "Progeny",
            header: false,
            tbar: tbarButtons,
            items: ypgSearchForm
        });
        ypgPanel.on("activate", function () {
            Ext.getDom("yo-panel").innerHTML = "";
            Ext.getDom("yo-form").innerHTML = "";
            Ext.getDom("sample-search-result-list").innerHTML = "";
            if (ypgLoaded == false) {
                ypgLoaded = true;
                goSearch(0, searchParam, searchOption);
            }
            renderYPGSearchResult();
        });
    }

    function postYPGStrain(createNew) {
        var ypgPostJson = new Object();
        var strainName = Ext.getCmp("ypgStrainNameId").getValue();
        ypgPostJson["ypgKey"] = strainName;
        ypgPostJson["ypgStatus"] = Ext.getCmp("ypgStatusId").getValue();
        ypgPostJson["ypgAlias"] = Ext.getCmp("ypgAliasId").getValue();
        ypgPostJson["ypgMatingType"] = Ext.getCmp("ypgMatingTypeId").getValue();
        ypgPostJson["ypgGenotype"] = Ext.getCmp("ypgGenotypeId").getValue();
        ypgPostJson["ypgParentA"] = Ext.getCmp("ypgParentAId").getValue();
        ypgPostJson["ypgParentAlpha"] = Ext.getCmp("ypgParentAlphaId").getValue();
        ypgPostJson["ypgCrossingRef"] = Ext.getCmp("ypgCrossingRefId").getValue();
        ypgPostJson["ypgSiblings"] = Ext.getCmp("ypgSiblingsId").getValue();
        ypgPostJson["ypgTetrad"] = Ext.getCmp("ypgTetradId").getValue();
        ypgPostJson["ypgBoxNumber"] = Ext.getCmp("ypgBoxNumberId").getValue();
        ypgPostJson["ypgPosition"] = Ext.getCmp("ypgPositionId").getValue();
        ypgPostJson["ypgDateFrozen"] = Ext.getCmp("ypgDateFrozenId").getRawValue();
        ypgPostJson["ypgComments"] = Ext.getCmp("commentsYPGId").getRawValue();
        var strainOp = "create";
        var ypgCallback = function() {
            limsadmin_obj["limsadminYpgCount"] = ypgCount; 
            limsadmin_obj['limsadminYpgMaxNum'] = ypgMaxNum;
			postSolrUpdates(limsadmin_obj, function(){
                Ext.Msg.alert('Info', "YPG Strain " + strainName + ' Added Successfully');
                Ext.getDom("yo-form").innerHTML = "";
                goSearch(0, strainName, "ypgFields");
            });
         };
        if (!createNew) {
            strainOp = "annotations";
            ypgCallback = function() {
                Ext.Msg.alert('Info', strainName + ' Updated Successfully');
                var searchResultsButton = Ext.getCmp("showYPGSearchResultsId");
                searchResultsButton.disable();
            };
        }
        postSolrUpdates(ypgPostJson, ypgCallback);
    }

    function loadCreateYPGStrain(ypgHash, callback) {
        var createNew = true;
        var portalPanel = new Ext.Panel({});
        var buttons = [
            {
                id: 'createButton',
                name: 'createButton',
                text: 'Create',
                listeners: {click:
                        function() {
                            if (validateCreateUpdateYPG()) {
                                postYPGStrain(createNew);
                            }
                        }
                }
            }
        ];
        if (ypgHash != null) {
            if (ypgHash.genotype != undefined && ypgHash.genotype == 'Record Deleted') {
                buttons = [];
            } else {
                buttons = [
                    {
                        id: 'updateYPGButtonId',
                        name: 'updateYPGButton',
                        text: 'Update',
                        listeners: {click:
                                function() {
                                    if (validateCreateUpdateYPG()) {
                                        postYPGStrain(!createNew);
                                    }
                                }
                        }
                    }
                ];
            }
            if (ypgHash.sequencingData == null) {
                ypgHash.sequencingData = "";
            }
            if (ypgHash.phenotypeData == null) {
                ypgHash.phenotypeData = "";
            }
            if (ypgHash.comments == null) {
                ypgHash.comments = "";
            }
            if (ypgHash.rnaData == null) {
                ypgHash.rnaData = "";
            }
            if (ypgHash.proteomicsData == null) {
                ypgHash.proteomicsData = "";
            }
            if (ypgHash.imaging == null) {
                ypgHash.imaging = "";
            }
            if (ypgHash.status == null || ypgHash.status == "") {
                ypgHash.status = "VIABLE";
            }
            portalPanel = new Ext.Panel({
                id: "yadImagePanelId",
                autoHeight: true,
                title: "Strain Meta Data",
                autoWidth: true,
                header: true,
                html: "<a href='javascript:placeHolder()'><img src='images/search-blue.png' border='0'>Image View Portal</a>"
                        + "&nbsp;" + "<a href='javascript:placeHolder()'><img src='images/search-blue.png' border='0'>Sequence View Portal</a>"
                        + "&nbsp;" + "<a href='javascript:placeHolder()'><img src='images/search-blue.png' border='0'>Proteomics View Portal</a>"
                        + "&nbsp;" + "<a href='javascript:placeHolder()'><img src='images/search-blue.png' border='0'>RNA View Portal</a>"
            });
        } else {
            ypgHash = new Object();
            var ypgMaxInt = parseInt(ypgMaxNum);
            ypgMaxInt = ypgMaxInt + 1;
            var ypgCountInt = parseInt(ypgCount);
            ypgCountInt = ypgCountInt + 1;
            ypgCount = ypgCountInt + "";
            ypgHash.name = 'YPG ' + ypgMaxInt;
            ypgMaxNum = ypgMaxInt + "";
            initYPGStrainJson(ypgHash);
        }
        var progenyStatusStore = new Ext.data.SimpleStore({
            fields: ['key', 'value'],
            data : getProgenyStatusArray()
        });
        var matingTypeStore = new Ext.data.SimpleStore({
            fields: ['key', 'value'],
            data : getMatingTypeArray()
        });
        var comboMatingType = new Ext.form.ComboBox({
            store: matingTypeStore,
            name: 'ypgMatingType',
            id: 'ypgMatingTypeId',
            fieldLabel: 'Mating Type',
            displayField:'value',
            valueField:'key',
            typeAhead: true,
            mode: 'local',
            triggerAction: 'all',
            value:ypgHash.matingType,
            forceSelection:true,
            selectOnFocus:true
        });

        ypgForm = new Ext.form.FormPanel({
            id: 'ypgForm',
            method: 'POST',
            autoHeight: true,
            autoScroll: true,
            border: true,
            buttonAlign: 'left',
            tbar: [
                {
                    id: 'detailSpotlightYPGId',
                    disabled: !createNew,
                    text: 'Spotlight',
                    icon: "images/add-green.png",
                    cls:'x-btn-text-icon',
                    tooltip: 'Add YPG to spotlight',
                    listeners: {
                        click: function() {
                            var selectedArray = [ypgHash.name, ypgHash.name, ypgHash.crossingRef];
                            sptlght.utils.SpotlightUtils.setSelectedRecord(selectedArray);
                            sptlght.utils.SpotlightUtils.setSource("ypg");
                            sptlght.utils.SpotlightUtils.handleAddToSpotlight();
                        }
                    }
                }
            ],
            buttons: buttons,
            items: [
                new Ext.form.FieldSet({
                    autoHeight: true,
                    border: false,
                    items: [
                        new Ext.form.TextField({
                            id: "ypgStrainNameId",
                            fieldLabel: "Key",
                            name: "ypgStrainName",
                            value: ypgHash.name,
                            width: 500,
                            readOnly: true,
                            allowBlank: false,
                            listeners: {
                                render: function(c) {
                                    Ext.QuickTips.register({
                                        target: c,
                                        title: '',
                                        text: 'Required: A YPG number that uniquely identifies this version of this strain (for example duplicate copies of the same strain are' +
                                              ' assigned different YPG numbers), the field is system generated and can not be changed.'
                                    });
                                }
                            }
                        }),
                        new Ext.form.ComboBox({
                            store: progenyStatusStore,
                            id: 'ypgStatusId',
                            fieldLabel: 'Status',
                            displayField:'value',
                            valueField:'key',
                            typeAhead: true,
                            mode: 'local',
                            triggerAction: 'all',
                            value:ypgHash.status,
                            forceSelection:true,
                            selectOnFocus:true,
                            listeners: {
                                render: function(c) {
                                    Ext.QuickTips.register({
                                        target: c,
                                        title: '',
                                        text: 'Progeny state, possible values are BLANK, VIABLE, INVIABLE'
                                    });
                                }
                            }
                        }),
                        new Ext.form.TextField({
                            id: "ypgAliasId",
                            fieldLabel: "Alias",
                            value: ypgHash.alias,
                            width: 500,
                            allowBlank: true,
                            listeners: {
                                render: function(c) {
                                    Ext.QuickTips.register({
                                        target: c,
                                        title: '',
                                        text: 'Optional: a more meaningful string description of string, such as an alias from the kruglyak collection'
                                    });
                                }
                            }
                        }),
                        comboMatingType,
                        new Ext.form.TextField({
                            id: "ypgGenotypeId",
                            fieldLabel: "Genotype",
                            name: "ypgStrainGenotype",
                            value: ypgHash.genotype,
                            width: 500,
                            allowBlank: false
                        }),
                        new Ext.form.TextField({
                            id: "ypgParentAId",
                            fieldLabel: "Parent A",
                            name: "ypgParentA",
                            value: ypgHash.parentA,
                            width: 500,
                            allowBlank: true
                        }),
                        new Ext.form.TextField({
                            id: "ypgParentAlphaId",
                            fieldLabel: "Parent Alpha",
                            name: "ypgParentAlpha",
                            value: ypgHash.parentAlpha,
                            width: 500,
                            allowBlank: true
                        }),
                        new Ext.form.TextField({
                            id: "ypgSiblingsId",
                            fieldLabel: "Sister spores",
                            name: "ypgSiblings",
                            value: ypgHash.siblings,
                            width: 500,
                            allowBlank: true,
                            listeners: {
                                render: function(c) {
                                    Ext.QuickTips.register({
                                        target: c,
                                        title: '',
                                        text: 'A ist of the three keys of sister spores (Dudley NV crossings produce tetrads with 4 (A B C D) spores) of this particular progeny'
                                    });
                                }
                            }
                        }),
                        new Ext.form.TextField({
                            id: "ypgTetradId",
                            fieldLabel: "Tetrad",
                            value: ypgHash.tetrad,
                            width: 500,
                            allowBlank: true
                        }),
                        new Ext.form.TextField({
                            id: "ypgCrossingRefId",
                            fieldLabel: "Crossing ref",
                            name: "ypgStrainCrossing",
                            value: ypgHash.crossingRef,
                            width: 500,
                            allowBlank: true
                        }),

                        new Ext.form.TextField({
                            id: "ypgBoxNumberId",
                            fieldLabel: "Box number",
                            name: "ypgBoxNumber",
                            value: ypgHash.boxNumber,
                            width: 500,
                            allowBlank: false
                        }),
                        new Ext.form.TextField({
                            id: "ypgPositionId",
                            fieldLabel: "Position",
                            name: "ypgPosition",
                            value: ypgHash.position,
                            width: 500,
                            allowBlank: true
                        }),
                        new Ext.form.DateField({
                            id: "ypgDateFrozenId",
                            fieldLabel: "Date frozen",
                            name: "ypgDateFrozen",
                            value: ypgHash.dateFrozen,
                            size: 20,
                            allowBlank: true
                        }),
                        {
                            xtype:'htmleditor',
                            id:'commentsYPGId',
                            value: ypgHash.comments,
                            fieldLabel:'Comments ' + '<br><i><font size=-2>Relevant information about the strain not covered in other fields</font></i>',
                            height:100,
                            labelSeparator: '',
                            anchor:'98%',
                            listeners: {
                                activate: function(e) {
                                    if (ypgHash.comments == undefined || ypgHash.comments == "") {
                                        e.execCmd('delete');
                                    }
                                }/*,
                                 'initialize': function(f) {
                                 if (document.all) {
                                 f.iframe.attachEvent("onblur", function(){on_editor_blur("commentsYPGId");});
                                 }
                                 else {
                                 f.iframe.contentDocument.addEventListener("blur", function(){on_editor_blur("commentsYPGId");}, false);
                                 }
                                 }*/
                            }
                        }
                    ]
                })
            ]
        });
        callback();
    }

    function renderYPGSearchResult() {
        var searchResultsButton = Ext.getCmp("showYPGSearchResultsId");
        if (searchResultsButton != null || searchResultsButton != undefined) {
            searchResultsButton.disable();
        }
        pagingBar = new Ext.PagingToolbar({
            pageSize: 12,
            store: ypgStore,
            displayInfo: true,
            displayMsg: 'Displaying strains {0} - {1} of {2}',
            emptyMsg: "No strains to display"
        });
        var searchResultsGrid = new Ext.grid.GridPanel({
            id: "ypgSearchResultsId",
            store: ypgStore,
            columns: getYPGSearchColumnHeaders(),
            stripeRows: true,
            autoHeight: true,
            width: 750,
            title: 'ProgenyStrains',
            renderTo: "sample-search-result-list",
            tbar: [
                {
                    id: 'ypg2CSVId',
                    text: 'Export2CSV',
                    icon: "images/check-green.png",
                    cls:'x-btn-text-icon',
                    tooltip: 'Export search results to csv',
                    listeners: {click:
                            function() {
                                Dudley.lims.YPGStrain.toCSV();
                            }
                    }
                }
            ],
            bbar: pagingBar
        });
        searchResultsGrid.on("celldblclick", function (g, ri, ci, e) {
            var searchResultsButton = Ext.getCmp("showYPGSearchResultsId");
            searchResultsButton.enable();
            Ext.getCmp("imageYPGId").enable();
            ypgHash = new Object();
            populateYPGJson(ypgHash, g);
            var resourceUri = "/addama-rest/dudley-sample/path/datasource/YPG/" + ypgHash.name;
            Ext.Ajax.request({
                url: resourceUri + "/mayUpdate",
                method: "GET",
                params: {
                    "user_uri": LoggedInUser.userUri
                },
                success: function() {
                    loadCreateYPGStrain(ypgHash, function() {
                        ypgFormRender();
                    });
                },
                failure: function() {
                    eventManager.fireStatusMessageEvent({ text: "Read only access allowed", level: "info" });
                    loadCreateYPGStrain(ypgHash, function() {
                        var updateYPGButton = Ext.getCmp("updateYPGButtonId");
                        if (updateYPGButton != undefined) {
                            updateYPGButton.hidden = true;
                        }
                        var deleteYPGButton = Ext.getCmp("deleteYPGButtonId");
                        if (deleteYPGButton != undefined) {
                            deleteYPGButton.hidden = true;
                        }
                        ypgFormRender();
                    });
                }
            });
        });
        searchResultsGrid.on("rowcontextmenu", onMessageContextMenu);
    }

    function onMessageContextMenu(grid, rowIndex, e) {
        var activePage = Math.ceil((pagingBar.cursor + pagingBar.pageSize) / pagingBar.pageSize);
        var realIndex = (activePage - 1) * pagingBar.pageSize + rowIndex;
        sptlght.utils.SpotlightUtils.setSelectedRecord(ypgStore.allData.items[realIndex].json);
        sptlght.utils.SpotlightUtils.setSource("ypg");
        e.preventDefault();
        e.stopEvent();
        var coords = e.getXY();
        spotlightMenu.showAt([coords[0], coords[1]]);
    }

    function ypgFormRender() {
        Dudley.lims.samplemgr.getHousingPanel().activate(ypgPanel);
        Ext.getDom("sample-search-result-list").innerHTML = "";
        Ext.getDom("yo-form").innerHTML = "";
        ypgForm.render("yo-form");
    }
    
    function setYpgAdmin(jsonObj){
    	limsadmin_obj =  jsonObj;
    	ypgCount = jsonObj.limsadminYadCount;
                        ypgMaxNum = jsonObj.limsadminYpgMaxNum;                       
                        ypgHash = null;
                        Ext.getCmp("showYPGSearchResultsId").enable();
                        loadCreateYPGStrain(ypgHash, function() {
                            Ext.getDom("sample-search-result-list").innerHTML = "";
                            Ext.getDom("yo-form").innerHTML = "";
                            ypgForm.render("yo-form");
                        });
     }                   


    // public
    return {
        initYPG: function(failedCB) {
            initYPGStore(failedCB, function() {
                eventManager.fireStatusMessageEvent({ text: "Finishing init YPG Store", level: "info" });
            });
        },

        getYPGPanel: function() {
            loadYPGPanel();
            return ypgPanel;
        },

        getYPGPanelInst: function() {
            return ypgPanel;
        },
        toCSV: function() {
            var crossRef = myYPGData[0][6];
            var csvText = "ypgKey,ypgMatingType,ypgGenotype,ypgParentA,ypgParentAlpha,ypgSiblings,ypgCrossingRef,ypgBoxNumber,ypgPosition,ypgDateFrozen,ypgComments,ypgTetrad,ypgStatus" + breakDelimiter;
            myYPGData.sort(function(a, b) {
                return a[0] - b[0];
            });
            for (var c = 0; c < myYPGData.length; c++) {
                var cArray = myYPGData[c];
                for (var ci = 0; ci < cArray.length; ci++) {
                    if (!cArray[ci]) {
                        cArray[ci] = "";
                    }
                    if (cArray[14] == "") {
                        cArray[14] = "VIABLE";
                    }
                    cArray[ci] = cArray[ci] + "";
                    cArray[ci] = cArray[ci].replace(/'/g, "");
                    cArray[ci] = cArray[ci].replace(/YCR /g, "YCR");
                    cArray[ci] = cArray[ci].replace(/YPG /g, "YPG");
                    cArray[ci] = cArray[ci].replace(/YO /g, "YO");
                    cArray[ci] = cArray[ci].replace(/YAD /g, "YAD");
                    cArray[ci] = '"' + cArray[ci] + '"';
                }
                csvText = csvText + "" + cArray[1] + "," + cArray[2] + "," + cArray[3] + "," + cArray[4] + "," + cArray[5]
                        + "," + cArray[11] + "," + cArray[6]
                        + "," + cArray[7] + "," + cArray[10] + "," + cArray[8] + "," + cArray[9] + "," + cArray[13] + "," + cArray[14] + breakDelimiter;
            }
            export2Csv(crossRef + "_YPGResults.csv", csvText, "ypg2Csv");
        },

        setSearchParam: function(myParam) {
            searchParam = myParam;
        },

        setSearchOption: function(myOption) {
            searchOption = myOption;
        },

        setSearchParams: function(myParam, myOption) {
            searchParam = myParam;
            searchOption = myOption;
        },

        setYPGLoaded: function(boo) {
            ypgLoaded = boo;
        },

        getYPGStore: function() {
            return ypgStore;
        },

        loadNewYPG: function() {
            Ext.getDom("yo-form").innerHTML = "";
            if (LoggedInUser.userUri == "/addama-users/users/public@systemsbiology.org") {
                Ext.Msg.alert("warning", "You not have permission to create new ypgs");
            } else {
               	getSolrLimsAdmin(setYpgAdmin);            	
            }
        },
        loadYPG: function(ypgKey) {
            var uri = "/addama-rest/dudley-sample/path/datasource/YPG/" + ypgKey + "/annotations";
            Ext.Ajax.request({
                url: uri,
                method: "GET",
                success: function(response) {
                    ypgHash = Ext.util.JSON.decode(response.responseText);
                    ypgHash.name = ypgKey;
                    loadCreateYPGStrain(ypgHash, function() {
                        Ext.getDom("sample-search-result-list").innerHTML = "";
                        Ext.getDom("yo-form").innerHTML = "";
                        ypgForm.render("yo-form");
                    });
                },
                failure: function() {
                    eventManager.fireStatusMessageEvent({ text: "Error retrieving data for " + ypgKey, level: "error" });
                    Ext.Msg.alert("error", "Error retrieving data for " + ypgKey);
                }
            });
        },
        loadYPGSearch: function() {
            goSearch(0, searchParam, searchOption);
        },
        loadSearchResult: function() {
            Ext.getDom("sample-search-result-list").innerHTML = "";
            renderYPGSearchResult();
        },
        viewImages: function() {
            if (ypgHash == null) {
                loadImageWindow(null);
            } else {
                loadImageWindow(ypgHash.name);
            }
        },
        setArrayData: function(data) {
                    myYPGData = data;
         }
    };
}();
